package com.LeeCode;



/**
 * 重排链表
 */

public class Code143 {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        ListNode head = Utils.arrayToListNode(arr);
        new Code143().reorderList(head);
    }

    public void reorderList(ListNode head) {
        ListNode slow = head, fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }

        ListNode head1 = reverse(slow);

        slow = head;
        fast = head1;
        while (fast != null) {
            head1 = head1.next;
            fast.next = slow.next;
            slow.next = fast;
            slow = fast.next;
            fast = head1;
        }
        slow.next = null;
        Utils.printListNode(head);
    }

    private ListNode reverse(ListNode head) {
        ListNode prev = null, cur = head;
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
        }
        return prev;
    }
}
